using System.Linq;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;

namespace LS.UnityExtensions.Editor
{
    public class PreloadScriptableObjectsBuildProcess : IPreprocessBuildWithReport
    {
        public int callbackOrder { get; }
        public void OnPreprocessBuild(BuildReport report)
        {
            var preloadAssets = PlayerSettings.GetPreloadedAssets().ToList();
            string[] guids = AssetDatabase.FindAssets($"t:PreloadScriptableObject");
            foreach (var guid in guids)
            {
                string path = AssetDatabase.GUIDToAssetPath(guid);
                var asset = AssetDatabase.LoadAssetAtPath<PreloadScriptableObject>(path);
                if (!preloadAssets.Contains(asset))
                {
                    preloadAssets.Add(asset);
                }
            }
            
            PlayerSettings.SetPreloadedAssets(preloadAssets.Where(a=>a != null).ToArray());
        }
    }
}
